#include <jni.h>
#include <string>
#include "ffmpeg_kit_wrapper.h"
#include "logger.h"

// 全局FFmpegKit包装器实例
static std::unique_ptr<FFmpegKitWrapper> g_ffmpegKitWrapper;

extern "C" JNIEXPORT jboolean JNICALL
Java_com_figo_player_FigoPlayerPlugin_initializeFFmpeg(JNIEnv *env, jobject thiz) {
    g_ffmpegWrapper = std::make_unique<FFmpegWrapper>();
    return g_ffmpegWrapper->initialize();
}

extern "C" JNIEXPORT jboolean JNICALL
Java_com_figo_player_FigoPlayerPlugin_openMedia(JNIEnv *env, jobject thiz, jstring filePath) {
    if (!g_ffmpegWrapper) {
        return JNI_FALSE;
    }
    
    const char* path = env->GetStringUTFChars(filePath, nullptr);
    bool result = g_ffmpegWrapper->openMedia(std::string(path));
    env->ReleaseStringUTFChars(filePath, path);
    
    return result ? JNI_TRUE : JNI_FALSE;
}

extern "C" JNIEXPORT jobject JNICALL
Java_com_figo_player_FigoPlayerPlugin_getMediaInfo(JNIEnv *env, jobject thiz) {
    if (!g_ffmpegWrapper) {
        return nullptr;
    }
    
    auto info = g_ffmpegWrapper->getMediaInfo();
    
    // 创建Java对象
    jclass mediaInfoClass = env->FindClass("com/figo/player/MediaInfo");
    jmethodID constructor = env->GetMethodID(mediaInfoClass, "<init>", "(IIIDILjava/lang/String;)V");
    
    jstring codec = env->NewStringUTF(info.codec.c_str());
    jobject mediaInfo = env->NewObject(mediaInfoClass, constructor,
                                     info.width, info.height, info.duration, 
                                     info.bitrate, codec);
    
    env->DeleteLocalRef(codec);
    return mediaInfo;
}

extern "C" JNIEXPORT jboolean JNICALL
Java_com_figo_player_FigoPlayerPlugin_play(JNIEnv *env, jobject thiz) {
    if (!g_ffmpegWrapper) {
        return JNI_FALSE;
    }
    
    return g_ffmpegWrapper->play() ? JNI_TRUE : JNI_FALSE;
}

extern "C" JNIEXPORT jboolean JNICALL
Java_com_figo_player_FigoPlayerPlugin_pause(JNIEnv *env, jobject thiz) {
    if (!g_ffmpegWrapper) {
        return JNI_FALSE;
    }
    
    return g_ffmpegWrapper->pause() ? JNI_TRUE : JNI_FALSE;
}

extern "C" JNIEXPORT jboolean JNICALL
Java_com_figo_player_FigoPlayerPlugin_stop(JNIEnv *env, jobject thiz) {
    if (!g_ffmpegWrapper) {
        return JNI_FALSE;
    }
    
    return g_ffmpegWrapper->stop() ? JNI_TRUE : JNI_FALSE;
}

extern "C" JNIEXPORT jboolean JNICALL
Java_com_figo_player_FigoPlayerPlugin_seek(JNIEnv *env, jobject thiz, jdouble time) {
    if (!g_ffmpegWrapper) {
        return JNI_FALSE;
    }
    
    return g_ffmpegWrapper->seek(time) ? JNI_TRUE : JNI_FALSE;
}

extern "C" JNIEXPORT void JNICALL
Java_com_figo_player_FigoPlayerPlugin_setVolume(JNIEnv *env, jobject thiz, jdouble volume) {
    if (g_ffmpegWrapper) {
        g_ffmpegWrapper->setVolume(volume);
    }
}

extern "C" JNIEXPORT void JNICALL
Java_com_figo_player_FigoPlayerPlugin_cleanup(JNIEnv *env, jobject thiz) {
    if (g_ffmpegWrapper) {
        g_ffmpegWrapper->cleanup();
        g_ffmpegWrapper.reset();
    }
}
